<template>
  <el-cascader   size="small"  placeholder="选择所属分类" v-bind="$attrs" @change="onChange" :value="values" :options="categories" filterable change-on-select>
  </el-cascader>
</template>
<script>
export default {
  name: "category-cascader",
  inheritAttrs: false,
  model: {
    prop: "categoryIds",
    event: "changeCategory"
  },

  methods: {
    onChange(v) {
      if (v) {
        this.$emit("changeCategory", v.join(","));
      }
    }
  },
  props: {
    categoryIds: {
      default: "",
      tyep: String
    },
    hasRoot: {
      default: false,
      tyep: Boolean
    }
  },
  computed: {
    values() {
      if (this.categoryIds && this.categoryIds.trim().length > 0) {
        let ids = this.categoryIds.trim().replace(/^,|,$/g, "");
        if (ids) {          
          return ids.split(",");
        }
      }
      return [];
    }
  },
  created() {
    this.$get("/admin/goods_category/tree").then(info => {
      if (this.hasRoot) {
        this.categories.push({
          value: "0",
          code:'',
          label: "(顶级分类)"
        });
      }
      this.categories.push(...info);
    });
  },
  data() {
    return {
      categories: []
    };
  }
};
</script>
